// -*- coding: utf-8 -*-
frappe.ui.form.on('Scrap Issue', {
    refresh: function(frm) {
        // 添加操作按钮
        if (frm.doc.docstatus === 0) {
            // 草稿状态
            if (frm.doc.status === "草稿") {
                frm.add_custom_button(__('提交审批'), function() {
                    submit_for_approval(frm);
                }, __('操作'));
            }
        } else if (frm.doc.docstatus === 1) {
            // 已提交状态
            if (frm.doc.status === "已审核") {
                frm.add_custom_button(__('打印出库单'), function() {
                    print_issue_document(frm);
                }, __('操作'));
            }
        }
        
        // 添加审核按钮（仅限Scrap Manager角色）
        if (frm.doc.status === "待审核" && frappe.user.has_role("Scrap Manager")) {
            frm.add_custom_button(__('批准'), function() {
                approve_issue(frm, true);
            }, __('审批'));
            
            frm.add_custom_button(__('拒绝'), function() {
                approve_issue(frm, false);
            }, __('审批'));
        }
        
        // 添加查看历史记录按钮
        frm.add_custom_button(__('查看历史记录'), function() {
            show_transaction_history(frm);
        }, __('查看'));
    },
    
    // 仓库字段变更事件
    warehouse: function(frm) {
        if (!frm.doc.warehouse) return;
        
        // 验证仓库状态
        frappe.call({
            method: 'frappe.client.get_value',
            args: {
                doctype: 'Scrap Warehouse',
                filters: { name: frm.doc.warehouse },
                fieldname: ['status']
            },
            callback: function(r) {
                if (r.message && r.message.status !== '启用') {
                    frappe.msgprint({
                        title: '仓库状态异常',
                        message: `仓库 ${frm.doc.warehouse} 状态为 ${r.message.status}，无法使用`,
                        indicator: 'red'
                    });
                    frm.set_value('warehouse', '');
                }
            }
        });
    },
    
    // 余料列表字段变更事件
    scrap_materials: function(frm) {
        // 计算总数量
        calculate_total_quantity(frm);
    },
    
    // 出库单编号字段变更事件
    issue_id: function(frm) {
        // 格式化编号为大写
        if (frm.doc.issue_id) {
            frm.set_value('issue_id', frm.doc.issue_id.toUpperCase());
        }
    },
    
    // 表单加载时
    onload: function(frm) {
        // 保存原始状态
        frm.original_status = frm.doc.status;
        
        // 设置子表库位字段的过滤器
        frm.set_query('location', 'scrap_materials', function() {
            return get_location_filter_for_issue(frm);
        });
    },
    
    // 表单保存前
    before_save: function(frm) {
        // 计算总数量
        calculate_total_quantity(frm);
    }
});

// 子表事件
frappe.ui.form.on('Scrap Issue Item', {
    // 添加行时
    scrap_materials_add: function(frm, cdt, cdn) {
        // 设置默认值
        let row = locals[cdt][cdn];
        if (!row.quantity) {
            frappe.model.set_value(cdt, cdn, 'quantity', 1);
        }
    },
    
    // 删除行时
    scrap_materials_remove: function(frm) {
        // 重新计算总数量
        calculate_total_quantity(frm);
    },
    
    // 数量变更时
    quantity: function(frm, cdt, cdn) {
        // 重新计算总数量
        calculate_total_quantity(frm);
    }
});

// 提交审批函数
function submit_for_approval(frm) {
    frappe.confirm('确定要提交审批吗？', function() {
        frappe.call({
            method: 'submit_for_approval',
            doc: frm.doc,
            callback: function(r) {
                if (!r.exc) {
                    frappe.show_alert({
                        message: '已提交审批',
                        indicator: 'green'
                    });
                    frm.reload_doc();
                }
            }
        });
    });
}

// 审批处理函数
function approve_issue(frm, approved) {
    let action = approved ? '批准' : '拒绝';
    frappe.confirm(`确定要${action}此出库单吗？`, function() {
        frappe.call({
            method: 'approve',
            doc: frm.doc,
            args: {
                approve: approved
            },
            callback: function(r) {
                if (!r.exc) {
                    frappe.show_alert({
                        message: `已${action}`,
                        indicator: approved ? 'green' : 'red'
                    });
                    frm.reload_doc();
                }
            }
        });
    });
}

// 计算总数量函数
function calculate_total_quantity(frm) {
    let total_quantity = 0;
    frm.doc.scrap_materials.forEach(function(item) {
        total_quantity += flt(item.quantity);
    });
    frm.set_value('total_quantity', total_quantity);
}

// 显示余料详情函数
function show_scrap_material_details(frm, scrap_material) {
    frappe.call({
        method: 'frappe.client.get',
        args: {
            doctype: 'Scrap Material',
            name: scrap_material
        },
        callback: function(r) {
            if (r.message) {
                let scrap = r.message;
                let dialog = new frappe.ui.Dialog({
                    title: `余料详情 - ${scrap.scrap_id}`,
                    fields: [
                        {
                            fieldname: 'scrap_id',
                            fieldtype: 'Data',
                            label: '余料编号',
                            read_only: 1,
                            default: scrap.scrap_id
                        },
                        {
                            fieldname: 'warehouse',
                            fieldtype: 'Link',
                            label: '仓库',
                            options: 'Scrap Warehouse',
                            read_only: 1,
                            default: scrap.warehouse
                        },
                        {
                            fieldname: 'location',
                            fieldtype: 'Link',
                            label: '库位',
                            options: 'Scrap Location',
                            read_only: 1,
                            default: scrap.location
                        },
                        {
                            fieldname: 'material_type',
                            fieldtype: 'Link',
                            label: '材料类型',
                            options: 'Material Type',
                            read_only: 1,
                            default: scrap.material_type
                        },
                        {
                            fieldname: 'material_name',
                            fieldtype: 'Data',
                            label: '材料名称',
                            read_only: 1,
                            default: scrap.material_name
                        },
                        {
                            fieldname: 'color_pattern',
                            fieldtype: 'Data',
                            label: '花色',
                            read_only: 1,
                            default: scrap.color_pattern
                        },
                        {
                            fieldname: 'length',
                            fieldtype: 'Float',
                            label: '长度',
                            read_only: 1,
                            default: scrap.length
                        },
                        {
                            fieldname: 'width',
                            fieldtype: 'Float',
                            label: '宽度',
                            read_only: 1,
                            default: scrap.width
                        },
                        {
                            fieldname: 'thickness',
                            fieldtype: 'Float',
                            label: '厚度',
                            read_only: 1,
                            default: scrap.thickness
                        },
                        {
                            fieldname: 'quantity',
                            fieldtype: 'Float',
                            label: '数量',
                            read_only: 1,
                            default: scrap.quantity
                        },
                        {
                            fieldname: 'uom',
                            fieldtype: 'Link',
                            label: '单位',
                            options: 'UOM',
                            read_only: 1,
                            default: scrap.uom
                        },
                        {
                            fieldname: 'status',
                            fieldtype: 'Select',
                            label: '状态',
                            options: '可用\n已出库\n已报废',
                            read_only: 1,
                            default: scrap.status
                        }
                    ],
                    primary_action: function() {
                        dialog.hide();
                    }
                });
                dialog.show();
            }
        }
    });
}

// 显示事务历史记录函数
function show_transaction_history(frm) {
    frappe.call({
        method: 'frappe.client.get_list',
        args: {
            doctype: 'Scrap Transaction',
            filters: {
                reference_doctype: 'Scrap Issue',
                reference_name: frm.doc.name
            },
            fields: ['transaction_type', 'transaction_date', 'scrap_material', 'quantity', 'notes'],
            order_by: 'transaction_date desc'
        },
        callback: function(r) {
            if (r.message && r.message.length > 0) {
                let dialog = new frappe.ui.Dialog({
                    title: '事务历史记录',
                    fields: [
                        {
                            fieldname: 'transaction_history',
                            fieldtype: 'HTML',
                            options: ''
                        }
                    ],
                    primary_action: function() {
                        dialog.hide();
                    }
                });
                
                let html = '<table class="table table-bordered">' +
                    '<thead>' +
                        '<tr>' +
                            '<th>事务类型</th>' +
                            '<th>事务日期</th>' +
                            '<th>余料</th>' +
                            '<th>数量</th>' +
                            '<th>备注</th>' +
                        '</tr>' +
                    '</thead>' +
                    '<tbody>';
                
                r.message.forEach(function(transaction) {
                    html += '<tr>' +
                        '<td>' + transaction.transaction_type + '</td>' +
                        '<td>' + transaction.transaction_date + '</td>' +
                        '<td><a href="#" class="scrap-link" data-scrap="' + transaction.scrap_material + '">' + transaction.scrap_material + '</a></td>' +
                        '<td>' + transaction.quantity + '</td>' +
                        '<td>' + transaction.notes + '</td>' +
                    '</tr>';
                });
                
                html += '</tbody></table>';
                
                dialog.fields_dict.transaction_history.$wrapper.html(html);
                
                // 添加余料链接点击事件
                dialog.$wrapper.find('.scrap-link').on('click', function() {
                    let scrap_material = $(this).data('scrap');
                    dialog.hide();
                    show_scrap_material_details(frm, scrap_material);
                });
                
                dialog.show();
            } else {
                frappe.msgprint('没有找到相关的事务记录');
            }
        }
    });
}

// 打印出库单函数
function print_issue_document(frm) {
    window.open(frappe.urllib.get_full_url("/printview?doctype=Scrap Issue&name=" + encodeURIComponent(frm.doc.name) + "&format=Standard&no_letterhead=0"));
}

// 库位过滤函数
function get_location_filter_for_issue(frm) {
    let filters = {
        status: '启用'
    };
    
    // 如果已选择仓库，则只显示该仓库下的库位
    if (frm.doc.warehouse) {
        filters['warehouse'] = frm.doc.warehouse;
    }
    
    return filters;
}